<template>
  <div class="indicator-tree-container">
    <!-- 头部 -->
    <div class="tree-header">
      <span class="tree-title">指标目录</span>
      <el-button 
        type="primary" 
        size="small" 
        icon="el-icon-plus"
        @click="handleAddRootNode"
        v-if="treeData.length === 0"
      >
        添加根节点
      </el-button>
    </div>
    
    <!-- 目录树 -->
    <div class="tree-content">
      <el-tree
        ref="treeRef"
        :data="treeData"
        :props="treeProps"
        node-key="pkid"
        :expand-on-click-node="false"
        :highlight-current="true"
        :default-expand-all="true"
        @node-click="handleNodeClick"
        class="indicator-tree"
      >
        <template #default="{ node, data }">
          <div class="tree-node">
            <span class="node-label">{{ node.label }}</span>
            <div class="node-actions">
              <el-button
                type="text"
                size="mini"
                icon="el-icon-plus"
                @click.stop="handleAddChild(data, node)"
                title="新增子节点"
              />
              <el-button
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click.stop="handleEdit(data, node)"
                title="编辑"
              />
              <el-button
                type="text"
                size="mini"
                icon="el-icon-delete"
                @click.stop="handleDelete(data, node)"
                title="删除"
                class="delete-btn"
              />
            </div>
          </div>
        </template>
      </el-tree>
    </div>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <!-- 新增子目录时显示的字段 -->
        <template v-if="dialogType === 'addChild'">
          <el-form-item label="当前目录节点">
            <el-input :value="getCurrentNodePath()" disabled />
          </el-form-item>
          <el-form-item label="目录层级" prop="level">
            <el-select v-model="formData.level" placeholder="请选择目录层级" style="width: 100%">
              <el-option label="当前目录" :value="1" />
              <el-option label="子目录" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="目录名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入目录名称" />
          </el-form-item>
          <el-form-item label="目录类型" prop="type">
            <el-select
              v-model="formData.type"
              placeholder="请选择"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in nodeTypeDict"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="排序号" prop="orderIndex">
            <el-input-number 
              v-model="formData.orderIndex" 
              :min="0" 
              controls-position="right"
              style="width: 100%"
              placeholder="请输入排序号"
            />
          </el-form-item>
        </template>
        
        <!-- 编辑目录时显示的字段 -->
        <template v-else-if="dialogType === 'edit'">
          <el-form-item label="目录名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入目录名称" />
          </el-form-item>
          <el-form-item label="目录类型" prop="type">
            <el-select
              v-model="formData.type"
              placeholder="请选择"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in nodeTypeDict"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="排序号" prop="orderIndex">
            <el-input-number 
              v-model="formData.orderIndex" 
              :min="0"
              controls-position="right"
              style="width: 100%"
              placeholder="请输入排序号"
            />
          </el-form-item>
        </template>
        
        <!-- 添加根节点时显示的字段（保留原有功能） -->
        <template v-else-if="dialogType === 'add'">
          <el-form-item label="节点名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入节点名称" />
          </el-form-item>
          <el-form-item label="目录类型" prop="type">
            <el-select
              v-model="formData.type"
              placeholder="请选择"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in nodeTypeDict"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  queryIndicatorConfigTree, 
  addIndicatorCatalog, 
  updateIndicatorCatalog, 
  deleteIndicatorCatalog 
} from '@/api/screen-management/indicator-config'

export default {
  name: 'IndicatorTree',
  data() {
    return {
      treeData: [],
      treeProps: {
        children: 'children',
        label: 'catalogName'
      },
      selectedNode: null,
      selectedData: null,
      
      // 对话框相关
      dialogVisible: false,
      dialogTitle: '',
      dialogType: '', // 'add', 'edit', 'addChild'
      formData: {
        name: '',
        description: '',
        level: '',
        type: '',
        orderIndex: 1
      },
      formRules: {
        name: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '请选择目录层级', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'blur' }
        ]
      },
      
      // 当前操作的节点信息
      currentParentData: null,
      currentParentNode: null,
      currentEditData: null,
      currentEditNode: null,
      
      // ID生成器
      nextId: 5,
      defaultType: '',
      rootId: '-1',
      nodeTypeDict: [
        {
          label: '普通',
          value: 1
        },
        {
          label: '特殊',
          value: 2
        },
        {
          label: 'content',
          value: 3
        }
      ]   
    }
  },
  mounted() {
    this.getIndicatorConfigTree()
  },
  methods: {
    getIndicatorConfigTree() {
      queryIndicatorConfigTree().then(res => {
        this.treeData = res.data[0].children
        // this.rootId = res.data[0].pkid
        // 数据加载完成后触发事件
        this.$emit('data-loaded', this.treeData)
      })
    },
    
    // 节点点击事件
    handleNodeClick(data, node) {
      this.selectedNode = node
      this.selectedData = data
      this.$emit('node-select', data, node)
    },
    
    // 添加根节点
    handleAddRootNode() {
      this.dialogType = 'add'
      this.dialogTitle = '添加根节点'
      this.formData = {
        name: '',
        description: ''
      }
      this.currentParentData = null
      this.currentParentNode = null
      this.dialogVisible = true
    },
    
    // 添加子节点
    handleAddChild(data, node) {
      this.dialogType = 'addChild'
      this.dialogTitle = '新增目录'
      // 获取下一个排序号
      const nextorderIndex = this.getNextorderIndex(data)
      this.formData = {
        name: '',
        description: '',
        level: '',
        type: '',
        orderIndex: nextorderIndex
      }
      this.currentParentData = data
      this.currentParentNode = node
      this.dialogVisible = true
    },
    
    // 编辑节点
    handleEdit(data, node) {
      console.log('data :>> ', data)
      this.dialogType = 'edit'
      this.dialogTitle = '编辑目录'
      this.formData = {
        pkid: data.pkid,
        name: data.catalogName,
        description: data.description || '',
        level: data.level || '',
        orderIndex: data.orderIndex,
        type: Number(data.type) || ''
      }
      console.log('this.formData :>> ', this.formData)
      this.currentEditData = data
      this.currentEditNode = node
      this.dialogVisible = true
    },
    
    // 删除节点
    handleDelete(data, node) {
      this.$confirm('确定要删除该节点吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteIndicatorCatalog(data.pkid).then(res => {
          if (res.success) {
            this.$message.success('删除成功') 
            this.getIndicatorConfigTree()
          } else {
            this.$message.error(res.message)
          }
        }).catch(err => {
          this.$message.error('删除失败')
        })
      }).catch(() => {
        // 取消删除
      })
    },
    
    // 对话框确认
    handleConfirm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          if (this.dialogType === 'add') {
            // 添加根节点
            const params = {
              catalogName: this.formData.name,
              type: this.formData.type,
              parentId: this.getParentId(),
              orderIndex: this.formData.orderIndex
            }
            addIndicatorCatalog(params).then(res => {
              this.$message.success('添加成功')
              // 重新加载树数据
              this.getIndicatorConfigTree()
              this.dialogVisible = false
            }).catch(err => {
              this.$message.error('添加失败')
            })
          } else if (this.dialogType === 'addChild') {
            // 添加子节点
            const params = {
              catalogName: this.formData.name,
              type: this.formData.type,
              parentId: this.getParentId(),
              orderIndex: this.formData.orderIndex
            }
            addIndicatorCatalog(params).then(res => {
              this.$message.success('新增目录成功')
              // 重新加载树数据
              this.getIndicatorConfigTree()
              this.dialogVisible = false
            }).catch(err => {
              this.$message.error('新增目录失败')
            })
          } else if (this.dialogType === 'edit') {
            // 编辑节点
            const params = {
              pkid: this.currentEditData.pkid,
              catalogName: this.formData.name,
              parentId: this.currentEditData.parentId,
              type: this.formData.type,
              orderIndex: this.formData.orderIndex
            }
            updateIndicatorCatalog(params).then(res => {  
              this.$message.success('编辑目录成功')
              this.getIndicatorConfigTree()
              this.dialogVisible = false
            }).catch(err => {
              this.$message.error('编辑目录失败')
            })
          }
        }
      })
    },
    
    // 对话框关闭
    handleDialogClose() {
      this.$refs.formRef?.resetFields()
      this.currentParentData = null
      this.currentParentNode = null
      this.currentEditData = null
      this.currentEditNode = null
    },
    
    // 获取当前节点路径（用于显示父节点信息）
    getCurrentNodePath() {
      if (!this.currentParentData) return ''
      
      // 构建节点路径
      let path = []
      let currentNode = this.currentParentNode
      
      // 向上遍历到根节点
      while (currentNode) {
        if (currentNode.data && currentNode.data.catalogName) {
          path.unshift(currentNode.data.catalogName)
        }
        currentNode = currentNode.parent
        // 如果到达根节点（parent为空或者parent.data为数组），停止
        if (!currentNode || Array.isArray(currentNode.data)) {
          break
        }
      }
      
      return path.join(' / ') || this.currentParentData.catalogName
    },
    
    // 获取父节点ID
    getParentId() {
      if (this.dialogType === 'addChild' && this.currentParentData) {
        // 根据目录层级选择来决定parentId
        if (this.formData.level === 1) {
          // 当前目录：parentId是该条数据的上一级pkid
          return this.getParentNodeId(this.currentParentNode)
        } else if (this.formData.level === 2) {
          // 子目录：当前pkid就是parentId
          return this.currentParentData.pkid
        }
      } else {
        console.log('this.rootId :>> ', this.rootId)
        // 如果是添加根节点或没有父节点，使用rootId
        return this.rootId
      }
    },
    
    // 获取当前节点的父节点ID
    getParentNodeId(currentNode) {
      if (!currentNode || !currentNode.parent) {
        // 如果没有父节点，返回rootId
        return this.rootId
      }
      
      // 如果父节点是根节点（parent.data是数组），返回rootId
      if (Array.isArray(currentNode.parent.data)) {
        return this.rootId
      }
      
      // 返回父节点的pkid
      return currentNode.parent.data.pkid || this.rootId
    },
    
    // 获取下一个排序号
    getNextorderIndex(parentData) {
      if (!parentData.children || parentData.children.length === 0) {
        return 1
      }
      
      // 找到最大的排序号
      const maxorderIndex = Math.max(...parentData.children.map(child => child.orderIndex || 0))
      return maxorderIndex + 1
    },
    
    // 对子节点按排序号排序
    sortChildren(children) {
      children.sort((a, b) => (a.orderIndex || 0) - (b.orderIndex || 0))
    },
    
    // 获取当前选中的节点
    getSelectedNode() {
      return {
        data: this.selectedData,
        node: this.selectedNode
      }
    },
    
    // 设置选中节点
    setCurrentNode(nodeId) {
      if (nodeId) {
        this.$refs.treeRef.setCurrentKey(nodeId)
      }
    },
    
    // 程序化设置选中节点（包括内部状态）
    setSelectedNode(nodeData) {
      if (nodeData) {
        // 设置树的当前选中key
        this.$refs.treeRef.setCurrentKey(nodeData.pkid)
        // 设置内部状态
        this.selectedData = nodeData
        this.selectedNode = null 
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.indicator-tree-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .tree-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    // padding: 16px 0;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 16px;
    
    .tree-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .tree-content {
    flex: 1;
    overflow: auto;
    
    .indicator-tree {
      :deep(.el-tree-node__content) {
        height: 36px;
      }
      
      .tree-node {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        padding-right: 8px;
        
        .node-label {
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .node-actions {
          opacity: 1;
          display: flex;
          align-items: center;
          
          .el-button {
            padding: 4px;
            margin-left: 4px;
            
            &.delete-btn {
              color: #f56c6c;
              
              &:hover {
                background-color: #fef0f0;
              }
            }
          }
        }
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>